package com.xiashitech.agent.instrumentation.base.exporter.inst;

import com.google.auto.service.AutoService;
import io.opentelemetry.exporter.zipkin.ZipkinSpanExporter;
import io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder;
import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties;
import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import zipkin2.reporter.Sender;
import zipkin2.reporter.okhttp3.OkHttpSender;

import java.time.Duration;

@AutoService(ConfigurableSpanExporterProvider.class)
public class XSExportConfigurableSpanExporterProvider implements ConfigurableSpanExporterProvider {
    @Override
    public SpanExporter createExporter(ConfigProperties configProperties) {
        System.out.println(" =============================  XSExportConfigurableSpanExporterProvider called  ====================");
        ZipkinSpanExporterBuilder builder = ZipkinSpanExporter.builder();

        String endpoint = configProperties.getString("otel.exporter.zipkin.endpoint");
        if (endpoint != null) {
            // 修改 url ，将其改为取到的IP，但在这里改，启动后就固定不变了，agent 起起停停，负载可能会不均匀
            builder.setEndpoint(endpoint);
        }

        Duration timeout = configProperties.getDuration("otel.exporter.zipkin.timeout");
        if (timeout != null) {
            builder.setReadTimeout(timeout);
        }

        // 将 dns 解析放到 OkHttpClient 中，应该会每次请求时解析 dns，可能会更均匀
        OkHttpSender.Builder sb = OkHttpSender.newBuilder()
                .endpoint(endpoint)
                .compressionEnabled(true) // true 为默认值
                .readTimeout(timeout==null ? 10000: (int) timeout.toMillis()); // 10s 为默认值
        sb.clientBuilder().dns(new XSBalanceDns()); // OkHttpClient.Builder，设定 dns
        Sender sender = sb.build();
        builder.setSender(sender);

        return builder.build(); // ZipkinSpanExporter
        //return new XSSpanExporter();
    }

    @Override
    public String getName() {
        return "xszipkin";
    }
}
